package gw.com.android.ui.positions;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigTypesDeal;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.ViewPagerAdapter;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.views.CommonTitleBar;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.view.BtnClickListener;
import www.com.library.view.LoadingProgress;

/**
 * 仓位界面
 */
public class MainTradeFragment extends PushMsgTabFragment {

    @BindView(R.id.main_tab_title_bar)
    CommonTitleBar mTitleBar;
    @BindView(R.id.main_user_info_view)
    AccountInfoView mAccountView;// 用户资金栏
    /**
     * 数据加载圈
     */
    @BindView(R.id.loading_progress_view)
    LoadingProgress mProgress;
    /**
     * 按钮组
     */
    @BindView(R.id.tabs)
    TabLayout mTabLayout;
    @BindView(R.id.viewpager)
    ViewPager mViewPager;
    private DataItemResult mTabTitles;
    private ViewPagerAdapter mAdapter;
    private String mCurrentTag = ConfigType.TAB_POSITION_TYPE;
    private PushMsgTabFragment mCurrentFragment = null; // 当前显示的fragment
    private PositionFragment mPositionFragment = null; // 持仓
    private PendingFragment mPendingFragment = null; // 委托
    private DealFragment mDealFragment = null; // 当日成交
    private ProfitFragment mProfitFragment = null;// 当日盈亏
    private MoreFragment mMoreFragment = null;// 更多

    public MainTradeFragment() {

    }

    public static MainTradeFragment newInstance() {
        MainTradeFragment fragment = new MainTradeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mCurrentTag = getArguments().getString("mCurTag");
            if (null == mCurrentTag || mCurrentTag.length() < 1) {
                mCurrentTag = ConfigType.TAB_POSITION_TYPE;
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_trade;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
        // 抢占点击事件，以便下层界面不可点击
        mProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

//        mTitleBar.setRightText(R.string.main_menu_item_order);
        mTitleBar.setAppTitle(R.string.main_menu_item_trade);
        mTitleBar.setLeftIcon(0);
        mTitleBar.setBtnClickListener(new BtnClickListener() {

            @Override
            public void onBtnClick(int viewID) {
                switch (viewID) {
                    case R.id.title_right_text:
                        MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "Title_new_Order");
                        DataItemDetail model = DataManager.instance().getTradeTickModel();
                        if (null != model) {
                            ActivityManager.showOrderActivity(getActivity(), model, AppContances.TRADE_TYPE_BUY, AppContances.TRADE_TYPE_FORM_TRADE);
                        } else {
                            final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(getActivity(), "", ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1021));
                            dialog.show();
                        }
                        break;
                }

            }
        });
    }

    @Override
    protected void initViewData() {
        mAccountView.updateData();
        ConfigTypesDeal mTypesDeal = new ConfigTypesDeal();
        mTabTitles = mTypesDeal.getTradeTypeList();
        mAdapter = new ViewPagerAdapter(mFragmentManager, mTabTitles, new ViewPagerAdapter.ShowFragmentListener() {
            @Override
            public PushMsgTabFragment showFragment(String type, int position) {
                return getFragment(position);
            }
        });
        mViewPager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(mViewPager);

        mViewPager.setOffscreenPageLimit(mTabTitles.getDataCount());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Logger.e("MainTradeFragment onPageSelected " + position);
                mCurrentFragment = getFragment(position);
                if (position == 4) {
                    mAccountView.setVisibility(View.GONE);
                } else {
                    mAccountView.setVisibility(View.VISIBLE);
                }
                MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "Trade_TypeChecked" + position);
                if (null != mCurrentFragment && mCurrentFragment instanceof SubFragment) {
                    ((SubFragment) mCurrentFragment).refreshViewData();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        showFragment(mCurrentTag);
    }

    /**
     * 切换fragment
     */
    public void showFragment(String tag) {
        Logger.i("MainTradeFragment changeViews " + tag);
        mCurrentTag = tag;
        if (tag.equals(ConfigType.TAB_POSITION_TYPE)) {
            mViewPager.setCurrentItem(0);
            mCurrentFragment = mPositionFragment;
        } else if (tag.equals(ConfigType.TAB_PENDING_TYPE)) {
            mViewPager.setCurrentItem(1);
            mCurrentFragment = mPendingFragment;
        } else if (tag.equals(ConfigType.TAB_DEAL_TYPE)) {
            mViewPager.setCurrentItem(2);
            mCurrentFragment = mDealFragment;
        } else if (tag.equals(ConfigType.TAB_PROFIT_TYPE)) {
            mViewPager.setCurrentItem(3);
            mCurrentFragment = mProfitFragment;
        } else if (tag.equals(ConfigType.TAB_TRADE_TYPE_MORE)) {
            mViewPager.setCurrentItem(4);
            mCurrentFragment = mMoreFragment;
        }
    }

    private PushMsgTabFragment getFragment(int position) {
        Logger.i("MainTradeFragment initFragment " + position + ", " + mCurrentTag);
        if (position == 0) {
            if (null == mPositionFragment) {
                mPositionFragment = PositionFragment.newInstance();
            }
            if (mCurrentTag.equals(ConfigType.TAB_POSITION_TYPE)) {
                mCurrentFragment = mPositionFragment;
            }
            return mPositionFragment;
        } else if (position == 1) {
            if (null == mPendingFragment) {
                mPendingFragment = PendingFragment.newInstance();
            }
            if (mCurrentTag.equals(ConfigType.TAB_PENDING_TYPE)) {
                mCurrentFragment = mPendingFragment;
            }
            return mPendingFragment;
        } else if (position == 2) {
            if (null == mDealFragment) {
                mDealFragment = DealFragment.newInstance();
            }
            if (mCurrentTag.equals(ConfigType.TAB_DEAL_TYPE)) {
                mCurrentFragment = mDealFragment;
            }
            return mDealFragment;
        } else if (position == 3) {
            if (null == mProfitFragment) {
                mProfitFragment = ProfitFragment.newInstance();
            }
            if (mCurrentTag.equals(ConfigType.TAB_PROFIT_TYPE)) {
                mCurrentFragment = mProfitFragment;
            }
            return mProfitFragment;
        } else if (position == 4) {
            if (null == mMoreFragment) {
                mMoreFragment = MoreFragment.newInstance();
            }
            if (mCurrentTag.equals(ConfigType.TAB_TRADE_TYPE_MORE)) {
                mCurrentFragment = mMoreFragment;
            }
            return mMoreFragment;
        }
        return mCurrentFragment;

    }

    /**
     * 显示隐藏加载圈
     */
    public void onTradeProgressVisible(boolean isVisible) {
        if (null != mProgress) {
            Logger.e("main trade progress is " + isVisible);
            if (isVisible) {
                mProgress.setVisibility(View.VISIBLE);
            } else {
                mProgress.setVisibility(View.GONE);
            }
        } else {
            Logger.e("main trade progress is null");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != mAccountView) {
            mAccountView.updateData();
        }
    }

    @Override
    public void registerRxBus() {
        Disposable accountRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_ACCOUNT_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail account) throws Exception {
                        if (null != mAccountView && !isHidden()) {
                            mAccountView.updateData();
                        }
                    }
                });

        bindSubscription(accountRegister);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            BaseActivity activity = (BaseActivity) getActivity();
            if (null != activity) {
                activity.setTransparentBar(false);
            }
            if (null != mCurrentFragment) {
                mCurrentFragment.onHiddenChanged(false);
            }
            mAccountView.updateData();
            onSendQuote();
        }
    }

    @Override
    public void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
    }

    @Override
    public void quoteServerNotice(Boolean isConntion) {
        super.quoteServerNotice(isConntion);
        if (isConntion) {
            ServerConnnectUtil.instance().cancelTask(true);
            if (isVisible() && null != mCurrentFragment && mCurrentFragment instanceof SubFragment) {
                ((SubFragment) mCurrentFragment).refreshViewData();
            }
        }
    }

    public void onProgressVisible(Boolean isVisible) {
        onTradeProgressVisible(isVisible);
        if (null != mCurrentFragment && mCurrentFragment instanceof SubFragment) {
            ((SubFragment) mCurrentFragment).onProgressVisible(!isVisible);
        }
    }
}
